package com.ls.lserp.modules.order.service;



import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.dbaccess.Dao.FinanceEntityMapper;
import com.ls.lserp.dbaccess.Entity.FinanceEntity;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.dao.BigcargoOrderDao;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.Quotation;
import com.ls.lserp.modules.order.entity.SizeColorQuantity;
import com.ls.lserp.modules.order.entity.StyleFit;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;
@Service
@Transactional(readOnly = false)
public class BigcargoOrderService extends CrudService<BigcargoOrderDao,BigcargoOrder>{

	//合同
	 @Autowired
	    private BigcargoOrderDao bigcargoOrderDao ;
	 
	 // 财务明细
	 @Autowired
	 private FinanceEntityMapper financeEntityMapper;
	// 审核表
	@Autowired
	    private AuditInfoDao  auditInfoDao;

	    /**
		 * 查询父项
		 * @param page
		 * @param user
		 * @return
		 */
	    public Page<BigcargoOrder> findBigcargoOrderList(Page<BigcargoOrder> page, BigcargoOrder bigcargoOrder) {
	        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
	        //designOption.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
	        // 设置分页参数
	    	bigcargoOrder.setPage(page);
	        // 执行分页查询
	        page.setList(bigcargoOrderDao.findList(bigcargoOrder));
	        return page;
	    }
	    
	    /**
		 * 查询一条数据
		 * 
		 * @param user
		 * @return
		 */
	    public BigcargoOrder findBigcargoOrder(BigcargoOrder bigcargoOrder){
	    	
	    	List<BigcargoOrder> orderList = bigcargoOrderDao.findOrderList(bigcargoOrder.getId());
	    	bigcargoOrder = bigcargoOrderDao.get(bigcargoOrder);
	    	List<BigcargoOrder> customerList = findCustomerList();
			bigcargoOrder.setOrderStyleList(customerList);
	    			if (orderList != null && orderList.size() > 0) {
	    				for (int i = 0; i < orderList.size(); i++) {
	    					SizeColorQuantity sizeColorQuantity = new SizeColorQuantity();
	    					StyleFit styleFit = new StyleFit();
	    					List<SizeColorQuantity> sizeList = bigcargoOrderDao.findIndentSize(orderList.get(i).getIndentID());
	    					List<StyleFit> styleFitList = bigcargoOrderDao.findStyleFit(orderList.get(i).getStyleID());
	    					if (sizeList!=null) {
	    						sizeColorQuantity.setSizeColorQuantityList(sizeList);
	    					}else {
	    						sizeColorQuantity.setSizeColorQuantityList(null);
	    					}
	    					if (styleFitList!=null) {
	    						styleFit.setStyleFitList(styleFitList);
	    					}else {
	    						styleFit.setStyleFitList(null);
	    					}
	    					orderList.get(i).setSizeColorQuantity(sizeColorQuantity);
	    					orderList.get(i).setStyleFit(styleFit);
	    					}
		    				bigcargoOrder.setBigcargoOrderList(orderList);
	    			} else {
	    				bigcargoOrder.setBigcargoOrderList(null);
	    			}
	    			
	    		
	    	return bigcargoOrder;
	    	
	    }
	    /**
		 * 查询客户数据
		 * 
		 * @param user
		 * @return
		 */
	    public List<BigcargoOrder> findCustomerList(){
	    	
	    	return bigcargoOrderDao.findCustomerList();
	    	
	    }
	    
	    /**
		 * 查询一条款式信息
		 * 
		 * @param user
		 * @return
		 */
	    public BigcargoOrder getStyle(BigcargoOrder bigcargoOrder){
	    	List<BigcargoOrder> sizeList = bigcargoOrderDao.findStyleSize(bigcargoOrder.getStyleID());
	    	//List<BigcargoOrder> fileList = bigcargoOrderDao.findStyleFileList(bigcargoOrder.getStyleID());
	    	bigcargoOrder = bigcargoOrderDao.getStyle(bigcargoOrder);
	    	bigcargoOrder.setBigcargoOrderList(sizeList);
	    	return bigcargoOrder;
	    	
	    }
	    
	    /**
		 * ID查询一条数据
		 * 
		 * @param user
		 * @return
		 */
	    public BigcargoOrder findByID(Long id){
	    	
	    	return bigcargoOrderDao.get(id);
	    }
	    
	    /**
		 * 新增/修改一条数据
		 * @param user
		 */
	    @Transactional(readOnly = false)
	    public void saveBigcargoOrder(BigcargoOrder bigcargoOrder) {
	    	// 判断新建编辑
	    			//若为null 执行插入语句（新建）
	    			if (bigcargoOrder.getId()==null){
	    				String shortName = bigcargoOrderDao.getShortName(bigcargoOrder.getOgnizationID());
	    				StringBuilder conCode = new StringBuilder();
	    				conCode.append("80");
	    				conCode.append(shortName);
	    				conCode.append(DateUtils.formatDate(new Date(), "yyyy"));
	    				conCode.append("10");
	    		        Sequence sequence=SequenceUtil.ognizationCode(conCode.toString(), "sequence_contract", 4);
	    		        bigcargoOrder.setContractNO(sequence.getReturnCode());
	    				bigcargoOrder.setStatus(ResourcesUtil.getConfig("reserver_meterial_wait_accept"));
	    				bigcargoOrder.preInsert();
	    				bigcargoOrderDao.insert(bigcargoOrder);
	    				bigcargoOrderDao.insertFile(bigcargoOrder);
	    				bigcargoOrderDao.insertContractFile(bigcargoOrder);
	    				bigcargoOrderDao.insertContractCustomer(bigcargoOrder);
	    				if (bigcargoOrder.getBigcargoOrderList()!=null) {
							for (int i = 0; i < bigcargoOrder.getBigcargoOrderList().size(); i++) {
								BigcargoOrder bigcargoOrder2 =  bigcargoOrder.getBigcargoOrderList().get(i);
								if (bigcargoOrder.getBigcargoOrderList().get(i).getStyleID()==0) {
									continue;
								}
								String indentAmount = bigcargoOrder2.getIndentAmount();
								String indentQuantity =	bigcargoOrder2.getIndentQuantity();
								String indentPrice = bigcargoOrder2.getIndentPrice();
								String indentExchangeRate = bigcargoOrder2.getIndentExchangeRate();
								indentAmount = indentAmount.replace(",", "");
								indentQuantity = indentQuantity.replace(",", "");
								indentPrice = indentPrice.replace(",", "");
								indentExchangeRate = indentExchangeRate.replace(",", "");
								bigcargoOrder2.setIndentAmount(indentAmount);
								bigcargoOrder2.setIndentQuantity(indentQuantity);
								bigcargoOrder2.setIndentPrice(indentPrice);
								bigcargoOrder2.setIndentExchangeRate(indentExchangeRate);
								Sequence sequence2=SequenceUtil.ognizationCode(bigcargoOrder.getContractNO(), "sequence_contract_order", 3);
								bigcargoOrder2.setIndentStatus(bigcargoOrder.getOrderStatus());
								bigcargoOrder2.setIndentDeliveryDate(bigcargoOrder.getContractDeliveryDate());
								bigcargoOrder2.setIndentIssueDate(bigcargoOrder.getContractIssueDate());
								bigcargoOrder2.setIndentLastShipDate(bigcargoOrder.getContractLastShipDate());
								bigcargoOrder2.preInsert();
								bigcargoOrder2.setIndentNO(sequence2.getReturnCode());
								bigcargoOrder2.setId(bigcargoOrder.getId());
								bigcargoOrderDao.insertOrder(bigcargoOrder2);
								bigcargoOrderDao.insertContractStyle(bigcargoOrder2);
								if (bigcargoOrder2.getSizeColorQuantity()!=null) {
									for (int j = 0; j < bigcargoOrder2.getSizeColorQuantity().getSizeColorQuantityList().size(); j++) {
										SizeColorQuantity sizeColorQuantity =  bigcargoOrder2.getSizeColorQuantity().getSizeColorQuantityList().get(j);
										if (sizeColorQuantity.getIndentSizeCD()==""||sizeColorQuantity.getIndentSizeCD()==null) {
											continue;
										}
										
									    String indentNumber =  sizeColorQuantity.getIndentNumber();
									    indentNumber = indentNumber.replace(",", "");
									    sizeColorQuantity.setIndentNumber(indentNumber);
										sizeColorQuantity.setContractID(bigcargoOrder.getId());
										sizeColorQuantity.setIndentID(bigcargoOrder2.getIndentID());
										sizeColorQuantity.setStyleID(bigcargoOrder2.getStyleID());
										sizeColorQuantity.preInsert();
										bigcargoOrderDao.insertSize(sizeColorQuantity);
										
									}
								}
							}
						}
	    			// 编辑
	    			}else{
	    				// 更新数据
	    				//审核通过
	    				if (ResourcesUtil.getConfig("reserver_meterial_ok").equals(bigcargoOrder.getStatus())) {
	    					if (bigcargoOrder.getBigcargoOrderList()!=null && bigcargoOrder.getBigcargoOrderList().size() > 0) {
	    						BigcargoOrder bigcargoOrder2 =  new BigcargoOrder();
	    						for (int i = 0; i < bigcargoOrder.getBigcargoOrderList().size(); i++) {
	    							bigcargoOrder2 =  bigcargoOrder.getBigcargoOrderList().get(i);
	    							String indentAmount = bigcargoOrder2.getIndentAmount();
									String indentPrice = bigcargoOrder2.getIndentPrice();
									indentAmount = indentAmount.replace(",", "");
									indentPrice = indentPrice.replace(",", "");
									bigcargoOrder2.setIndentAmount(indentAmount);
									bigcargoOrder2.setIndentPrice(indentPrice);
									bigcargoOrder2.preUpdate();
									bigcargoOrderDao.updateOrder(bigcargoOrder2);
	    						}
	    						FinanceEntity financeEntity = new FinanceEntity();
	    						financeEntity.setFinanceContractId(bigcargoOrder.getId());
	    						financeEntity.setFinanceCategory(ResourcesUtil.getConfig("financeCategory05"));
	    						//获取该合同的财务明细
	    						financeEntity = financeEntityMapper.getFinanceByContractInfo(financeEntity);
	    						//如果存在且未入账，则更新金额
	    						if (financeEntity != null && !ResourcesUtil.getConfig("financeStatus01").equals(financeEntity.getAccountsStatus())) {
	    							BigcargoOrder bOrder = bigcargoOrderDao.getContractAmount(bigcargoOrder);
	    							if (bOrder != null) {
	    								financeEntity.setCreditAmount(new BigDecimal(bOrder.getIndentAmount()));
	    								financeEntityMapper.updateByContractInfo(financeEntity);
									}
								}
	    					}
	    				//未审核或审核未通过
						}else {
							bigcargoOrder.preInsert();
							bigcargoOrderDao.update(bigcargoOrder);
							bigcargoOrderDao.deleteFile(bigcargoOrder);
							bigcargoOrderDao.deleteContractFile(bigcargoOrder);
							bigcargoOrderDao.deleteContractCustomer(bigcargoOrder.getId());
							bigcargoOrderDao.insertFile(bigcargoOrder);
							bigcargoOrderDao.insertContractFile(bigcargoOrder);
							bigcargoOrderDao.deleteSize(bigcargoOrder.getId());
							bigcargoOrderDao.deleteContractStyle(bigcargoOrder.getId());
							bigcargoOrderDao.delete(bigcargoOrder);
							bigcargoOrderDao.insertContractCustomer(bigcargoOrder);
							if (bigcargoOrder.getBigcargoOrderList()!=null && bigcargoOrder.getBigcargoOrderList().size() > 0) {
								for (int i = 0; i < bigcargoOrder.getBigcargoOrderList().size(); i++) {
									BigcargoOrder bigcargoOrder2 =  bigcargoOrder.getBigcargoOrderList().get(i);
									if (bigcargoOrder.getBigcargoOrderList().get(i).getStyleID()==0) {
										continue;
									}
									String indentAmount = bigcargoOrder2.getIndentAmount();
									String indentQuantity =	bigcargoOrder2.getIndentQuantity();
									String indentPrice = bigcargoOrder2.getIndentPrice();
									String indentExchangeRate = bigcargoOrder2.getIndentExchangeRate();
									indentAmount = indentAmount.replace(",", "");
									indentQuantity = indentQuantity.replace(",", "");
									indentPrice = indentPrice.replace(",", "");
									indentExchangeRate = indentExchangeRate.replace(",", "");
									bigcargoOrder2.setIndentAmount(indentAmount);
									bigcargoOrder2.setIndentQuantity(indentQuantity);
									bigcargoOrder2.setIndentPrice(indentPrice);
									bigcargoOrder2.setIndentExchangeRate(indentExchangeRate);
									Sequence sequence2=SequenceUtil.ognizationCode(bigcargoOrder.getContractNO(), "sequence_contract_order", 3);
									bigcargoOrder2.setIndentStatus(bigcargoOrder.getOrderStatus());
									bigcargoOrder2.setIndentDeliveryDate(bigcargoOrder.getContractDeliveryDate());
									bigcargoOrder2.setIndentIssueDate(bigcargoOrder.getContractIssueDate());
									bigcargoOrder2.setIndentLastShipDate(bigcargoOrder.getContractLastShipDate());
									bigcargoOrder2.preInsert();
									bigcargoOrder2.setIndentNO(sequence2.getReturnCode());
									bigcargoOrder2.setId(bigcargoOrder.getId());
									bigcargoOrderDao.insertOrder(bigcargoOrder2);
									bigcargoOrderDao.insertContractStyle(bigcargoOrder2);
									if (bigcargoOrder2.getSizeColorQuantity()!=null) {
										for (int j = 0; j < bigcargoOrder2.getSizeColorQuantity().getSizeColorQuantityList().size(); j++) {
											SizeColorQuantity sizeColorQuantity =  bigcargoOrder2.getSizeColorQuantity().getSizeColorQuantityList().get(j);
											if (sizeColorQuantity.getIndentSizeCD()==""||sizeColorQuantity.getIndentSizeCD()==null) {
												continue;
											}
											String indentNumber =  sizeColorQuantity.getIndentNumber();
											indentNumber = indentNumber.replace(",", "");
											sizeColorQuantity.setIndentNumber(indentNumber);
											sizeColorQuantity.setContractID(bigcargoOrder.getId());
											sizeColorQuantity.setIndentID(bigcargoOrder2.getIndentID());
											sizeColorQuantity.setStyleID(bigcargoOrder2.getStyleID());
											sizeColorQuantity.preInsert();
											bigcargoOrderDao.insertSize(sizeColorQuantity);
											
										}
									}
								}
							}
						}
	    		}			
	    }
	    
	    /**
	     * @Title: findAuditList
	     * @Description: 查询所有履历
	     * @param @param auditInfo
	     * @param @return
	     * @return List<AuditInfo> 
	     * @throws
	     */
	   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
		   AuditInfo audit = new AuditInfo();
		   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
		   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
	       // 执行查询
	       return audit;
	   }
	   /**
	    * @Title: getAuditResult
	    * @Description: 审核结果
	    * @param @param auditInfo
	    * @param @return
	    * @return 审核结果通过数
	    * @throws
	    */
	  
	  public long getAuditResult(AuditInfo auditInfo) {
		   
	      return auditInfoDao.findAuditAcceptCount(auditInfo);
	  }
	  
	  /**
		  * @Title: saveAudit
		  * @Description: 保存履历信息
		  * @param @param auditInfo
		  * @return void 
		  * @throws
		  */
		@Transactional(readOnly = false)
		public void saveAuditInfo(AuditInfo auditInfo,boolean isUpdateStatus) {
			
			 // 插入履历表
		     auditInfo.preInsert();
		     auditInfo.setAuditDate(new Date());
		     auditInfo.setAuditUserId(UserUtils.getUser().getId());
	         // 新建版本号赋值1
		     auditInfo.setVersion(1L);
		     auditInfoDao.insert(auditInfo);
		     
		     auditInfo.preUpdate();
		     if (auditInfo.getAuditResult()==0) {
		    	 auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
			}else if (auditInfo.getAuditResult()==1) {
				auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
			}
		     
		     bigcargoOrderDao.updateStatus(auditInfo);
		     
		}
}
